import { AsyncSeriesHook } from 'qx-util';
import {
  INavigationDesignModalContext,
  INavigationDesignModalOption,
  INavigationDesignModalParams,
} from '../../interface';

/**
 * 导航设计modal
 *
 * @author zhanghengfeng
 * @date 2023-07-25 21:07:32
 * @export
 * @class NavigationDesignModal
 */
export class NavigationDesignModal {
  /**
   * 当前选中项
   *
   * @author zhanghengfeng
   * @date 2023-07-25 14:07:59
   * @type {(string | null)}
   */
  selection: string | null = null;

  /**
   * 选中项对应的钩子列表
   *
   * @author zhanghengfeng
   * @date 2023-07-25 20:07:41
   * @type {Record<string, AsyncSeriesHook<{ dc: DcUtil }, INavigationDesignModalContext>>}
   */
  hooks: Record<string, AsyncSeriesHook<INavigationDesignModalParams, INavigationDesignModalContext>> = {};

  constructor(option: INavigationDesignModalOption) {
    if (option.selection) {
      this.selection = option.selection;
    }
  }

  /**
   * 执行注册的钩子列表，返回上下文信息
   *
   * @author zhanghengfeng
   * @date 2023-07-25 20:07:53
   * @param {*} [key=this.selection]
   * @return {*}  {Promise<INavigationDesignModalContext>}
   */
  async dismiss(
    key: string | null = this.selection,
    context: INavigationDesignModalContext = { allowClose: true },
    params: IParams = {},
  ): Promise<INavigationDesignModalContext> {
    if (!key) {
      return context;
    }
    if (this.hooks[key]) {
      await this.hooks[key].call(context, params);
    }
    return context;
  }

  /**
   * 注册当前选中项的钩子
   *
   * @author zhanghengfeng
   * @date 2023-07-25 11:07:32
   * @param {(context: INavigationDesignModalContext, param: { dc: DcUtil }) => Promise<void>} fn
   * @return {*}  {void}
   */
  tapPromise(fn: (context: INavigationDesignModalContext, param: INavigationDesignModalParams) => Promise<void>): void {
    if (!this.selection) {
      return;
    }
    if (!this.hooks[this.selection]) {
      this.hooks[this.selection] = new AsyncSeriesHook();
    }
    this.hooks[this.selection].tapPromise(fn);
  }

  /**
   * 清除指定的钩子列表
   *
   * @author zhanghengfeng
   * @date 2023-07-25 11:07:46
   * @return {*}  {void}
   */
  clear(key: string | null = this.selection): void {
    if (!key || !this.hooks[key]) {
      return;
    }
    delete this.hooks[key];
  }
}
